package com.chungkui.check.handler.insidecheck.impl;

import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.MatchExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import com.chungkui.check.handler.insidecheck.InsideCheck;
import com.chungkui.check.handler.insidecheck.InsideCheckFactory;
import com.chungkui.check.handler.insidecheck.ParamCheckUtils;
import com.chungkui.check.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author jason
 * @date 2020/3/28
 */
public class StringInsideCheckImpl implements InsideCheck {
    @Override
    public CheckResult check(Object field, List<MatchExpression> matchExpressions) {
        if (CollectionUtils.isNotEmpty(matchExpressions)) {
            Map<String, Object> params = JsonUtil.json2map((String) field);
            if (params != null) {
                CheckResult result = ParamCheckUtils.check(matchExpressions, params);
                if (!result.ifPass()) {
                    return result;
                }
            } else {
                List<Map<String, Object>> listParam = JsonUtil.jsonToObject((String) field, List.class);
                if (listParam != null) {
                    CheckResult result = InsideCheckFactory.check(listParam, null, matchExpressions);
                    if (!result.ifPass()) {
                        return result;
                    }
                }
            }
        }
        return new CheckResult(true);
    }

    @Override
    public boolean suport(Object field, InsideType type) {
        return field instanceof String;
    }
}
